package com.example.demo.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.auth.entity.Menu;
import com.example.demo.auth.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static cn.hutool.json.JSONUtil.toBean;

//  // get my info
//  UserInfo: '/user/info',
//  UserMenu: '/user/nav'
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @PostMapping("/info")
    public Mono<JSONObject> sms(@RequestBody Mono<User> user) {
        try {
            File file = ResourceUtils.getFile("/mock/role.json");
            JSONObject jsonObject = JSONUtil.readJSONObject(file, StandardCharsets.UTF_8);
            return Mono.just(jsonObject);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return Mono.empty();
    }

    @PostMapping("/nav")
    public Flux<Menu> smsErr(@RequestBody Mono<User> user) {
        try {
//            File file = ResourceUtils.getFile();
//            String content= FileUtil.readableFileSize(file);
            List menu = JSONUtil.readJSONArray(new File("/mock/menu.json"), StandardCharsets.UTF_8);
            return Flux.fromStream(menu.stream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Flux.empty();

    }

    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @RequestMapping("doLogin")
    public String doLogin(String username, String password) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        if("zhang".equals(username) && "123456".equals(password)) {
            StpUtil.login(10001);
            return "登录成功";
        }
        return "登录失败";
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }
}
